$(function() {
    Base.init();
});

var Base = {
    oTimer : '',
    iTimerOn : 0,
    spinner : '',
        
    init: function() { },
    
    /**
     * 메시지 레이어 박스 출력
     */
    messageIn: function(sMsg, textMode, iWidth, bOut)
    {
        if (sMsg == undefined) var sMsg = '메세지가 없습니다.';
        if (textMode == undefined) var textMode = 'msg';
        if (bOut == undefined) var bOut = true;;
        if (iWidth == undefined) var iWidth = 600;
        
        if ($('#box_message').attr('id') != undefined) {
            $('#box_message').remove();
            if (this.iTimerOn == 1) {
                clearTimeout(this.oTimer);
                this.iTimerOn = 0;
            }
        }
        
        var textStyle = '';
        if (textMode == 'error') {
            textStyle = 'color:red;';
        } else if (textMode == 'ok') {
            textStyle = 'color:green;';
        }

        var sHtml = '<div id="box_message" class="box" style="display:none; position:fixed; right:0px; margin-top:10px; width:'+iWidth+'px; '+textStyle+'">'+sMsg+'</div>';
        $('body').prepend(sHtml);
        $('#box_message').css({'float':'right', 'z-index':'10000'}).fadeIn('slow');
        
        if (bOut) {
            this.oTimer = setTimeout('Base.messageOut();', 3000);
            this.iTimerOn = 1;
        }
    },
    
    /**
     * 메시지 레이어 박스 제거
     */
    messageOut: function()
    {
        if ($('#box_message').attr('id') != undefined) {
            $('#box_message').fadeOut('slow');
            this.iTimerOn = 0;
        }
    },
    
    coverOn: function(opacity)
    {
        if(opacity==undefined) opacity = 0.7;
        if(!$('#cover').length)
        {
            $('body').append("<div id='cover' style='position:fixed;opacity:0.7;left:0;top:0;width:100%;z-index:1000;background-color:#000000;background-repeat:no-repeat;display:none;'></div>");
        }
        $('#cover').css({
            top:0,
            left:0,
            height:$(window).height(),
            'background-position':'center '+(($(window).height()-32)/2)+'px'
        });
        $('#cover').fadeIn(300);
        /*$('#cover').show().css('opacity',0).animate({
            opacity:opacity
        },300,'easeOutQuart');*/
    },
    
    coverOff: function()
    {
        $cover = $('#cover');
        $cover.fadeOut(300);
        $(window).unbind('resize.cover');
    },
    
    /**
     * 로딩 시작
     */
    spinOn: function()
    {
        Base.coverOn();
        
        $('body').append('<div id="el_spinner" style="position:absolute; top:50px; left:50px;"></div>');
        
        var opts = {
            lines: 14, // The number of lines to draw
            length: 11, // The length of each line
            width: 6, // The line thickness
            radius: 19, // The radius of the inner circle
            color: '#000', // #rgb or #rrggbb
            speed: 1, // Rounds per second
            trail: 56, // Afterglow percentage
            shadow: true // Whether to render a shadow
        };

        var target = document.getElementById('el_spinner');
        this.spinner = new Spinner(opts).spin(target);
    },
    
    /**
     * 로딩 멈춤
     */
    spinOff: function()
    {
        if ($('#el_spinner').attr('id') == 'el_spinner')  {
            //$('#el_spinner').remove();
            Base.coverOff();
            Base.spinner.stop();
        }
    },
    
    popon: function(url,id,width,base_focus)
    {
        Base.coverOn();
        html = "<div id='"+id+"' style='display:none; position:absolute;z-index:2000; width:"+width+"px'><div class='pop_content'></div></div>";
        $('body').append(html);
        tar = $('#'+id);
        tar.show('fade',function(){
            if(base_focus!=undefined) tar.find('.'+base_focus).focus();
            else 
            {
                tar.find('.base_focus').focus();
            }
        });
        
        tar.css({
            'top' : ($(window).height()-tar.height())/4 + (document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop) - 50,
            'left' : ($(window).width()-tar.width())/2,
            'z-index' : 2000
        });
        $(window).bind('scroll.popon resize.popon unhold.popon',function(){     
            tar.css({           
                'top' : ($(window).height()-tar.height())/4 + (document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop),
                'left' : ($(window).width()-tar.width())/2
            });
        });
        
        $('#cover').click(function(){ Base.popoff(tar); });
        $(document).bind('keydown.popon',function(e) {
            if(e.keyCode==27) Base.popoff(tar);
        });
        con = tar.find('.pop_content'); 
        $.get(url,function(t){
            if(!t.length) 
            {
                alert('오류가 발생했습니다');
                Base.popoff(tar);
                return;
            }
            con.html(t);
            tar.find('.btn_pop_close').click(function(){ Base.popoff(tar); });
            $(window).trigger('resize.popon');
        });
    },
    
    popoff: function(tar)
    {   
        $(document).unbind('keydown.popon');
        tar.hide('fade',function(){
            tar.remove();
        }); 
        $(window).unbind('scroll.popon resize.popon');
        Base.coverOff();
    },
    
    link: function(url)
    {
        location.href = url;
    },
    
    /**
     * 위치정보 검색(위도, 경도)
     */
    getLatLng: function(sAddress)
    {
        if (sAddress == undefined) return false;

        var oGeocoder = new google.maps.Geocoder();
        oGeocoder.geocode( { 'address' : sAddress }, function(results, status) {
            if( status == google.maps.GeocoderStatus.OK ) {
                $('#lat').attr('value', results[0].geometry.location.lat());
                $('#lng').attr('value', results[0].geometry.location.lng());
                $('#srh_latlng').attr('value', 'y');
            } else {
                alert("위치 정보를 검색할수 없습니다. 주소를 확인해주세요");
                return false;
            }
        });
    },
    
    showPlaceHolder: function(objId, sText)
    {
        if ($('#'+objId).attr('id') == objId) {
            $('#'+objId).attr('value', sText);
        }
    },
    
    hidePlaceHolder: function(objId)
    {
        if ($('#'+objId).attr('id') == objId) {
            $('#'+objId).attr('value', '');
        }
    },
    
    /**
     * 쿠키 조회
     */
    getCookie: function(name) {
        var aCookie = document.cookie.split(';');

        for(var i=0; i<aCookie.length; i++) {
            if ( aCookie[i].indexOf(name + '=') > -1 )  {
                 var splitData = aCookie[i].split('=');
                 return unescape(splitData[1]);
            }
        }
        return null;
    },

    /**
     * Array 쿠키 조회
     */
    getCookArr: function(key,arrayName) {
        var aCookie = document.cookie.split('; ');
        var ret = '';
        for (var i=0; i < aCookie.length; i++) {
            if(!arrayName) {
                if(aCookie[i].substring(0, key.length+1) == key+'=') {
                    ret = unescape(aCookie[i].substring(key.length+1));
                    break;
                }
            } else {
                if(aCookie[i].substring(0, arrayName.length+1) == arrayName+'=') {
                    var arCook = unescape(aCookie[i].substring(arrayName.length+1)).split('&');
                    for( var j=0; j < arCook.length; j++) {
                        if(arCook[j].substring(0, key.length+1) == key+'=') {
                            ret = unescape(arCook[j].substring(key.length+1));
                            break;
                        }
                    }
                }
            }
        }
        if(!ret) ret = '';
        return ret;
    },

    /**
     * 쿠키 등록
     */
    setCookie: function(name, value) {
        var argc = Base.setCookie.arguments.length;
        var argv = Base.setCookie.arguments;
        var expires = (argc > 2) ? argv[2] : 0;
        var path = (argc > 3) ? argv[3] : null;
        var domain = (argc > 4) ? argv[4] : null;
        var secure = (argc > 5) ? argv[5] : false;

        if(expires != 0) {
            var dd = new Date(expires * 1000);
            var expst = '; expires='+dd.toGMTString();
        } else expst = '';

        var cookstr = name + '=' + value +
            ((expires == 0) ? '' : (expst)) +
            ((path == null) ? '' : ('; path=' + path)) +
            ((domain == null) ? '' : ('; domain=' + domain)) +
            ((secure == true) ? '; secure' : '');
        document.cookie = cookstr;
    },

    /**
     * Array 쿠키 등록
     */
    setCookArr : function(key,value,arrayName,until) {
        var cookStr = '';
        var findArr = false;
        var findKey = false;
        var cnt = 0;

        var aCookie = document.cookie.split('; ');
        if(!until) until = 0;
        if( !arrayName ) { this.setCookie(key,value,until,'/'); return; }

        for (var i=0; i < aCookie.length; i++) {
            if(aCookie[i].substring(0, arrayName.length+1) != arrayName+'=') continue;

            cookStr = '';
            findArr = true;

            var arCook = aCookie[i].substring(arrayName.length+1).split('&');
            for( var j=0; j<arCook.length; j++) {
                if(arCook[j] == '') continue;

                if(arCook[j].substring(0, key.length+1) == key+'=') {
                    findKey = true;
                    if( cnt == 0 ) cookStr = (key + '=' + value);
                    else cookStr += ('&' + key + '=' + value);
                } else {
                    if(cnt == 0) cookStr = arCook[j];
                    else cookStr += ('&' + arCook[j]);
                }
                cnt++;
            }

            if( !findKey ) {
                if(cnt == 0) cookStr = (key + '=' + value);
                else cookStr += ('&' + key + '=' + value);
            }
        }

        if(!findArr) cookStr = (key + '=' + value);

        this.setCookie(arrayName,cookStr,until,'/');
    },
    
    /**
     * 로그인
     */
    login: function()
    {
        var aValid = [
              ['아이디', 'email', 'login_id', 0, 80]
              , ['비밀번호', 'eng_all_num', 'login_pass', 6, 20]
          ];
        
        var _check = FormValidation.checked(aValid);
        if (!_check) {
            return false;
        }
        
        var params = 'm=setLogin&'+$('#loginForm').serialize();

        $.ajax({
            type: 'POST',
            url: '/',
            dataType: 'json',
            data: params,
            success:function(data) {
                if (data.code == 200) {
                    //alert('정상적으로 처리되었습니다.');
                    window.location.href = '/';
                    
                } else {
                    alert('아이디가 없거나 비밀번호가 잘못 되었습니다. [ code : '+data.code+']');
                }
            }
        });
    }
};

(function($){
    $.fn.digits = function(){
        return this.each(function(){
            var r = /(^[+-]?\d+)(\d{3})/;
            while(r.test($(this).text())){ $(this).text( $(this).text().replace(/(^[+-]?\d+)(\d{3})/, "$1,$2")); }
        })
    }
})(jQuery);

String.prototype.is_image = function()
{
    var filter = /.jpg|.gif|.png|.bmp|.jpeg$/i;
    
    if(!filter.test(this)) return false;
    else return true;
};

String.prototype.is_number = function()
{
    var filter = /^[0-9]+$/;

    if(!filter.test(this)) return false;
    else return true;
};

String.prototype.is_email = function()
{
    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

    if(!filter.test(this)) return false; 
    else return true;
};

String.prototype.is_id = function()
{
    var filter = /^[A-Za-z0-9]+$/;

    if(!filter.test(this)) return false;
    else return true;
};

String.prototype.is_name = function()
{
    var special = new Array(":","\"","'","~","!","@","#","$","%","^","`","|","-",".","[","]");

    for(i=0; i< special.length;i++)
    {
        t = special[i];
        if(this.indexOf(t)!=-1) return false;
    }
    
    return true;
};

String.prototype.strip_space = function()
{
    return this.str_replace(" ","");
};

String.prototype.str_replace = function(src,dest)
{
    var reg = new RegExp(src, "gi");
    return this.replace(reg, dest);
};

String.prototype.trim = function() 
{
    return this.replace(/^\s+|\s+$/g,"");
};

String.prototype.ltrim = function() 
{
    return this.replace(/^\s+/,"");
};

String.prototype.rtrim = function() 
{
    return this.replace(/\s+$/,"");
};